﻿using DataAccess.Api;
using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class RoleController : BaseController
    {

        public ActionResult Index()
        {
            RoleDAL roleDAL = new RoleDAL();
            List<Role> roles = roleDAL.List(UserSession.user_id);
            return View(roles);
        }
        public ActionResult List()
        {
            return View();
        }
    

        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            RoleDAL roleDAL = new RoleDAL();

            Role role;
            if (id != 0 && id != 1)
            {
                role = roleDAL.Get(id);
            }
            else
            {
                role = new Role();
            }

            return View(role);
        }

        [HttpPost]
        public JsonResult Edit(FormCollection form)
        {
            dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(Request.Form.ToString()));

            RoleDAL roleDAL = new RoleDAL();

            Role role = new Role();

            if (int.Parse(obj.id.Value) != 0)
            {
               
               
                role = roleDAL.Get(int.Parse(obj.id.Value));

                role.name = obj.name.Value;
                role.state = int.Parse(obj.state.Value);

                bool boo = roleDAL.Update(role);

                return Json(new Result { State = boo, Message = boo ? "更新成功" : "更新失败" });
            }
            else
            {
                role.name = obj.name.Value;
                role.state = int.Parse(obj.state.Value);
                role.type = 40;
                role.promoter_id = UserSession.user_id;
                bool boo = roleDAL.Insert(role);

                return Json(new Result { State = boo, Message = boo ? "添加成功" : "添加失败" });
            }
        }

        [HttpGet]
        public ActionResult Set(int id = 0)
        {
            RoleDAL roleDAL = new RoleDAL();

            Role role;
            if (id != 0 && id != 1)
            {
                role = roleDAL.Get(id);
                if (role.type == 10 || role.type == 20 || role.type == 30)
                {
                    return Redirect("/roles.html");
                }
            }
            else
            {
                role = new Role();
            }

            return View(role);
        }

        [HttpPost]
        public JsonResult Set(FormCollection form)
        {
            dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(Request.Form.ToString()));

            RoleDAL roleDAL = new RoleDAL();
            if (obj.id == null)
            {
                return Json(new Result { State = false, Message = "参数错误" });
            }

            Role role = roleDAL.Get(int.Parse(obj.id.Value));

            if (role == null)
            {
                return Json(new Result { State = false, Message = "角色不存在" });
            }

            string ids = (obj.ids.Value).ToString();
            PermissioninRoleDAL permissioninRoleDAL = new PermissioninRoleDAL();
            bool boo = permissioninRoleDAL.SetPermissioninRole(int.Parse(obj.id.Value), ids.Split(',').ToList().ConvertAll<int>(x => int.Parse(x)));


            return Json(new Result { State = boo, Message = boo ? "设置成功" : "设置失败" });

        }



        [HttpGet]
        public JsonResult GetPermissions(int roleid)
        {

            PermissioninRoleDAL permissioninRoleDAL = new PermissioninRoleDAL();
            List<PermissioninRole> curPermissions = permissioninRoleDAL.GetCurPermissioninRoles(roleid);


            List<Permission> permissions = new PermissionDAL().GetPermissions();
            List<TreeModel> trees = new List<TreeModel>();
            trees = (from c in permissions where c.parent_id == 0 select new TreeModel { bizId = c.id, bizPId = c.parent_id, text = c.menu_name, href = "#node_" + c.id, tags = new List<string>(), nodes = new List<TreeModel>(), state = new State { Checked = curPermissions.Count(p => p.permission_id == c.id) > 0, disabled = false, expanded = true, selected = false } }).ToList();

            foreach (var item in trees)
            {
                GetChild(item, permissions, curPermissions);
            }

            Result result = new Result { State = true, Datas = trees, Message = "查询成功" };

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public void GetChild(TreeModel treeModel, List<Permission> list, List<PermissioninRole> curPermissions)
        {
            treeModel.nodes = (from c in list where c.parent_id == treeModel.bizId select new TreeModel { bizId = c.id, bizPId = c.parent_id, text = c.menu_name, href = "#node_" + c.id, tags = new List<string>(), nodes = new List<TreeModel>(), state = new State { Checked = curPermissions.Count(p => p.permission_id == c.id) > 0, disabled = false, expanded = true, selected = false } }).ToList();

            foreach (var item in treeModel.nodes)
            {
                GetChild(item, list, curPermissions);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Message()
        {
            return View();
        }
       /// <summary>
       /// 群发消息
       /// </summary>
        /// <param name="AU_NameS">代理账号(多个用逗号隔开)</param>
        /// <param name="picUrl">发送图片地址</param>
        /// <param name="sendContent">发送内容</param>
       /// <returns></returns>
        [HttpPost]
        public JsonResult PostMessage(string AU_NameS,string picUrl,string sendContent)
        { 
            Result res=new Result(){ State=false, Message="请求错误"};
            
            var auNames=AU_NameS.Split(',');
            if (string.IsNullOrEmpty(AU_NameS) || auNames.Length <= 0)
            {
                res.Message="接收对象不能为空";
            }
            else if(string.IsNullOrEmpty(picUrl)&&string.IsNullOrEmpty(sendContent))
            {
                  res.Message="发送图片或者内容不能为空！";
                
            }
            else{
                new RobotApiHelper().SendMessaging(UserSession.user_id.ToString(),AU_NameS,picUrl,sendContent);

                res.State=true;
                res.Message="已下达发送命令！";
            }
            return Json(res);
        }

        /// <summary>
        /// 转链
        /// </summary>
        /// <returns></returns>
        public ActionResult ConventLink()
        {
            return View();
        }
        /// <summary>
        /// 搜索关键词
        /// </summary>
        /// <returns></returns>
        public ActionResult SearchKeyWord()
        {
           // SearchKeyWordDAL.ListPage();
            return View();
        }
        /// <summary>
        /// 获取搜索关键词
        /// </summary>
        /// <returns></returns>
        public ActionResult getSearchKeyList()
        {
           

            int limit = XYD.Common.Request.GetFormInt("limit", 20);
            int offset = XYD.Common.Request.GetFormInt("offset", 1);
        

            if (limit > 100) { limit = 20; }
            string strWhere = " promoter_id="+UserSession.user_id;
            string orderbys = "";
            int count = 0;
            List<SearchKeyWord> Items = SearchKeyWordDAL.ListPage(strWhere, orderbys, limit, (offset / limit) + 1, out count);
            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            result.Datas = new PageData<SearchKeyWord> { Total = count, Rows = Items, PageIndex = (offset / limit) + 1, PageSize = limit };
            return Json(result);
        }
        /// <summary>
        /// 轮播图广告位
        /// </summary>
        /// <returns></returns>
        public ActionResult Tag()
        {
            return View(new DataAccess.DAL.TagsDAL().GetTagss());
        }
        /// <summary>
        /// 轮播图添加修改
        /// </summary>
        /// <returns></returns>
        public ActionResult TagAdd()
        {
            DataAccess.Models.Tags model = new Tags();
            if (XYD.Common.Request.GetQueryInt("id", 0) != 0)
            {
                model = new DataAccess.DAL.TagsDAL().GetTagss().Find(c => c.id == XYD.Common.Request.GetQueryInt("id", 0));
            }
            
            return View(model);
        }
        /// <summary>
        /// post添加修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public ActionResult AddTags()
        {

            DataAccess.Models.Tags model = new Tags();
            int id = XYD.Common.Request.GetFormInt("id", 0);

            if (XYD.Common.Request.GetFormInt("id", 0) != 0)
            {
                model = new DataAccess.DAL.TagsDAL().GetTagss().Find(c => c.id == id);
            }
            model.ImgUrl = XYD.Common.Request.GetFormString("ImgUrl");
            model.Sort = XYD.Common.Request.GetFormInt("Sort", 0);
            model.TagType = XYD.Common.Request.GetFormInt("TagType", 0);
            model.Title = XYD.Common.Request.GetFormString("Title");
            model.UpdateTime = DateTime.Now;
            model.Url = XYD.Common.Request.GetFormString("Url");
            model.promoter_id = UserSession.user_id;
            model.CreateDate = DateTime.Now;
            model.Des = "";
            model.State = 1;
            model.ProductList = XYD.Common.Request.GetFormString("productid");
            model.searchkeyword = XYD.Common.Request.GetFormString("searchkeyword");
            model.UrlType = XYD.Common.Request.GetFormString("source");
           
            if (XYD.Common.Request.GetFormInt("id", 0) != 0)
            {
                new DataAccess.DAL.TagsDAL().Update(model);
            }
            else
            {
               
                new DataAccess.DAL.TagsDAL().Insert(model);
            }
            return Redirect("/Tag.html");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult PasswordEdit()
        {
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdatePwd(string pwd,string pwd1)
        {
            PromoterDAL dal = new PromoterDAL();
            var model = dal.Get(base.UserSession.user_id);
            string pw1 = XYD.Common.EncodeSecurity.EncryptString(pwd);
            if (pw1 != model.Password)
            {
                return Json(new Result { State = false, Message = "原始密码不正确" });
            }
            model.Password = XYD.Common.EncodeSecurity.EncryptString(pwd1);
            if (dal.Update(model))
            {
                return Json(new Result { State = true, Message = "更新成功" });
            }
            return Json(new Result { State = false, Message = "更新失败" });
        }
    }
}